import message from "@/utils/message"
import { uploadFile } from "@/api/upload"

export function useUploadAvatar(uploadAvatarCb) {

    // 上传限制类型
    const types = ["image/jpeg", "image/png"]

    // 上传大小限制
    const limitSize = 2

    // 上传头像前
    const uploadAvatarBeforeHook = (file) => {
        if (!types.includes(file.type)) {
            message.error("文件必须是JPG或者PNG类型")
            return false
        } else if (file.size / 1024 / 1024 > limitSize) {
            message.error(`文件大小不能超过${limitSize}M`)
            return false
        }
        return true
    }

    // 上传头像
    const uploadAvatarHook = async (config, field) => {
        // FormData 对象
        const formData = new FormData()
        formData.append("file", config.file)
        try {
            const res = await uploadFile(formData)
            message.success(res.msg)
            uploadAvatarCb && uploadAvatarCb({ ...res, field })
        } catch (error) {
            message.error(error)
        }
    }

    return { uploadAvatarBeforeHook, uploadAvatarHook }
}